package com.version1_3.service.ThirdPart;

import com.alibaba.fastjson.JSON;
import com.util.property.Properties;
import com.version1_3.dao.ThirdPart.WeiXinDao;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kuibu on 15/12/28.
 */
@Service
public class WeiXinServiceImpl implements WeiXinService{
    private static final Logger LOGGER = Logger.getLogger(WeiXinServiceImpl.class);

    @Autowired
    private WeiXinDao weiXinDao;

    @Override
    public String getSignature(String url) {

        // 获取微信分享ticket
        String jsapiTicket = getWxShareTicket();

        // 获取时间戳
        long date = new Date().getTime();
        long timeStamp = date/1000;

        String noncestr = "haoransun";

        String string1 = "jsapi_ticket="+jsapiTicket+"&noncestr="+noncestr+"&timestamp="+timeStamp+"&url="+url;
        String signNature = DigestUtils.sha1Hex(string1);

        Map<String,Object> sign = new HashMap<>();
        sign.put("timeStamp",timeStamp);
        sign.put("signature",signNature);
        sign.put("ticket",jsapiTicket);

        return JSON.toJSONString(sign);
    }

    @Cacheable(value = {"WxShareCache"})
    public String getWxShareTicket(){

        String appId = Properties.Wx_appId;
        String secret = Properties.Wx_secret;

        // 获取accessToken
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
        String accessTokenJson = loadJson(accessTokenUrl);
        JSONObject jsonObject = JSONObject.fromObject(accessTokenJson);
        String accessToken = jsonObject.getString("access_token");

        // 获取ticket
        String jsapiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        String jsapiTicketJson = loadJson(jsapiTicketUrl);
        JSONObject jsonObject2 = JSONObject.fromObject(jsapiTicketJson);
        return jsonObject2.getString("ticket");
    }

    /*
    * 工具类方法
    */
    public static String loadJson (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            LOGGER.error(e);
        } catch (IOException e) {
            LOGGER.error(e);
        }
        return json.toString();
    }
}
